500. Keyboard Row

1. Question

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop",
  • the second row consists of the characters "asdfghjkl", and
  • the third row consists of the characters "zxcvbnm".

    img
    Image

2. Examples

Example 1:

Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]

Example 2:

Input: words = ["omk"]
Output: []

Example 3:

Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]

3. Constraints

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase).

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/keyboard-row 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

建表查表,主要还是复习了下continue和锚点。

class Solution {
  private static String[] strs = { "qwertyuiop", "asdfghjkl", "zxcvbnm" };
  private static int[] arr = new int[26];

  static {
    for (int i = 0; i < strs.length; i++) {
      for (char c : strs[i].toCharArray()) {
        arr[c - 'a'] = i;
      }
    }
  }

  public String[] findWords(String[] words) {
    List<String> list = new ArrayList<>();

    out: for (String word : words) {
      String bak = word;
      word = word.toLowerCase();
      int index = word.charAt(0) - 'a';
      if (index < 0 || index > 26) {
        break;
      }

      int idx = arr[index];
      for (int i = 1; i < word.length(); i++) {
        if (idx != arr[word.charAt(i) - 'a']) {
          System.out.println(word);
          continue out;
        }
      }
      list.add(bak);

    }

    return list.toArray(new String[list.size()]);
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""